package ks.packs.anotherDay;

import java.io.InputStream;
import java.util.List;
import java.util.Locale;

import net.daum.mobilead.MobileAdView;

import com.admob.android.ads.AdView;

import android.app.TabActivity;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.telephony.TelephonyManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.TabHost;
import android.widget.Toast;

public class tabView extends TabActivity {

	private static final int MY_DATA_CHECK_CODE = 4321;
	private TextToSpeech mTts;
	String query;
	AdView adViewAdMob;
	MobileAdView adViewAdam;
	private String countrySO;
	MultipleAd mAd;

	String sortOfDictionary;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		final TabHost tb = getTabHost();

		LayoutInflater.from(this).inflate(R.layout.tab, tb.getTabContentView(),
				true);

		Intent intent = getIntent();

		sortOfDictionary = intent
				.getStringExtra(getString(R.string.SORT_OF_DICTIONARY));
		query = intent.getStringExtra("query");

		tb.addTab(tb.newTabSpec("tab_test1").setIndicator("Definition")
				.setContent(R.id.view1));

		tb.addTab(tb.newTabSpec("tab_test2").setIndicator("Pronunciation")
				.setContent(R.id.view2));

		final WebView wv = (WebView) findViewById(R.id.web_holder);
		wv.getSettings().setJavaScriptEnabled(true);
		wv.setWebViewClient(new HelloWebViewClient()); // WebViewClient
		wv.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);

		wv.loadUrl(getUrl());

		Button listenBtn = (Button) findViewById(R.id.btn_tts);

		listenBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {

				startTTSActivity();

			}
		});

		Button btnListenNAVER = (Button) findViewById(R.id.btn_ttsNAVER);
		btnListenNAVER.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {

				doBackground db = new doBackground();
				db.execute(null);

			}
		});

		setCountryCode();

		adViewAdam = (MobileAdView) findViewById(R.id.adviewAdam);
		adViewAdMob = (AdView) findViewById(R.id.adviewAdmob);

		mAd = new MultipleAd(countrySO, adViewAdMob, adViewAdam);

		if (mAd.isKorea()) {

			mAd.initAdam(false, "308Z0CT12dd46458a1");
			mAd.displayAdam();

		} else {

			mAd.initAdMob(false);
			mAd.displayAdmob();
		}

	}

	private void setCountryCode() {

		TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
		countrySO = tm.getSimCountryIso();

	}

	void startTTSActivity() {

		mTts = new TextToSpeech(this, null);
		mTts.setLanguage(Locale.US);
		Intent checkIntent = new Intent();
		checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
		startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);

	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (requestCode == MY_DATA_CHECK_CODE) {
			if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {

				// success, create the TTS instance
				play();

				if (mAd.isKorea()) {

					mAd.displayAdam();

				} else {

					mAd.displayAdmob();
				}

			} else {

				// missing data, install it
				Intent installIntent = new Intent();
				installIntent
						.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
				startActivity(installIntent);

			}
		}
	}

	private void play() {

		mTts.speak(query, TextToSpeech.QUEUE_FLUSH, // Drop all pending entries
													// in the playback queue.
				null);
	}

	private class HelloWebViewClient extends WebViewClient {

		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {

			view.loadUrl(url);
			return true;

		}

	}

	protected void onResume() {

		super.onResume();

		if (mAd.isKorea()) {

			mAd.displayAdam();

		} else {

			mAd.displayAdmob();
		}
	}

	private class doBackground extends AsyncTask<String, String, String> {

		MediaPlayer mp;
		AudioManager am;
		List<String> urlList;

		@Override
		protected String doInBackground(String... params) {

			ksLog.d("start");

			mp = new MediaPlayer();
			am = (AudioManager) getSystemService(AUDIO_SERVICE);

			LinkGetter lg = new LinkGetter(null);
			urlList = lg.getLinks(getUrl());

			try {

				mp.setDataSource(urlList.get(0));
				mp.prepare();
				am.setStreamVolume(AudioManager.STREAM_MUSIC, 100, 0);

			} catch (Exception e) {

			}
			return null;
		}

		protected void onProgressUpdate(String... values) {

		}

		protected void onPreExecute() {

		}

		protected void onPostExecute(String result) {

			Toast.makeText(getApplicationContext(), "성공", Toast.LENGTH_LONG)
					.show();

			mp.start(); 

		}
	}

	private String getUrl() {
		String RequestedUrl = null;

		if (sortOfDictionary.compareTo(getString(R.string.ENG_TO_KOREAN)) == 0) {

			RequestedUrl = "http://m.endic.naver.com/search.nhn?query=" + query;

		} else if (sortOfDictionary
				.compareTo(getString(R.string.KOREAN_TO_KOREAN)) == 0) {

			RequestedUrl = "http://krdic.naver.com/search.nhn?kind=&query="
					+ query;

		}

		else if (sortOfDictionary.compareTo(getString(R.string.KOREAN_TO_ENG)) == 0) {

			RequestedUrl = "http://m.endic.naver.com/search.nhn?query=" + query;

		}

		else if (sortOfDictionary.compareTo(getString(R.string.ENG_TO_ENG)) == 0) {

			RequestedUrl = "http://m.endic.naver.com/search.nhn?isOnlyViewEE&query="
					+ query;

		}

		return RequestedUrl;

	}

}
